# coding: utf-8
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import auth

from zabbix_api import ZabbixAPI, ZabbixAPIException


def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    else:
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('/')
            # return render(request, "login.html")
        else:
            return render(request, "login.html")


@login_required
def index(request):
    return render(request, 'zabbixs/index.html')


@login_required
def add(request):
    context = request.POST
    username = context['username']
    password = context['password']
    customer_name = context['cu']
    url = 'https://zabbix-qa.service.chinanetcloud.com'
    zapi = ZabbixAPI(server=url)
    zscreens = CreateZabbixScreen(zapi, username, password, customer_name)
    info = zscreens.Login()
    HostIDs = zscreens.GetHostID()
    HostList = zscreens.graphsForScreens(HostIDs)
    info = zscreens.create_screen(HostList)

    # return HttpResponse(template.render(context, request))
    return HttpResponse(info)


@login_required
def del_screen(request):
    context = request.POST
    username = context['username']
    password = context['password']
    customer_name = context['cu']
    url = 'https://zabbix-qa.service.chinanetcloud.com'
    zapi = ZabbixAPI(server=url)
    zscreens = CreateZabbixScreen(zapi, username, password, customer_name)
    info = zscreens.Login()
    HostIDs = zscreens.GetHostID()
    HostList = zscreens.graphsForScreens(HostIDs)
    del_info = zscreens.delete_screen(HostList)

    # return HttpResponse(template.render(context, request))
    return HttpResponse(del_info)


class CreateZabbixScreen(object):
    def __init__(self, zapi, username, password, customer_name):
        self.zapi = zapi
        self.Username = username
        self.Password = password
        self.CustomerName = customer_name

    # create zabbix screens
    def Login(self):
        try:
            self.zapi.login(self.Username, self.Password)
            return "Login successfully"

        except ZabbixAPIException, e:
            error_str = "Error:Name or Password is wrong"
            return error_str

    def GetHostID(self):
        try:
            GroupID = self.zapi.hostgroup.get({ "output": "groupid", "filter": { "name": self.CustomerName} })[0]['groupid']
        except IndexError as msg:
            error_str = "Unable find the customer " + self.CustomerName
            return error_str
        HostIDs = self.zapi.host.get({ "output": "hostid", "groupids" : [ GroupID ]})
        if len(HostIDs) == 0:
            error_str = "No server find in group " + self.CustomerName
            return error_str
        hostids =[]
        for i in HostIDs:
            hostids.append(i['hostid'])
        return hostids

    def getGraphs(self, hostid):
        graphs = {}
        selected = '0'
        for graph in self.zapi.graph.get({ "output": "extend", "hostids":hostid }):
            graphs[graph['name']] = (graph['graphid'], selected)
        return graphs

    def graphsForScreens(self, hosts):
        hosts.sort()
        if not hosts:
            print "hosts list is empty, exit..."
            sys.exit(1)
        graphs_stand_list = [ 'CPU %', 'Memory Usage','IOStat', 'Vmstat Swap In-Out',
                        'Ethx Network Traffic',
                        'Nginx', 'Apache', 'PHP-FPM Processes',
                        'MySQL*Connections', 'MySQL*Queries', 'MySQL*InnoDB',
                        'Tomcat*Heap Memory usage', 'Tomcat*Worker Threads', 'Tomcat*Sessions',
                        'Java*Heap Memory usage', 'Java*Worker Threads', 'Java*Sessions',
                        'HaProxy back/front session',
                        'Redis*Connections',
                        'Memcache*Connections',
                        'MongoDB*Queries-Requests', 'MongoDB*Connections', 'MongoDB*Performance'
                        'Postgres*Connections', 'Postgres*Cache Hit/Read'
                        ]
        try:
            from collections import OrderedDict
        except ImportError:
            from ordereddict import OrderedDict
        graphs_dict = OrderedDict()

        for hostid in hosts:
            host_graphs_list = []
            graphs = self.getGraphs(hostid)
            graphsKeys = graphs.keys()
            for key in graphsKeys:
                for g in graphs_stand_list:
                    g_list = g.split("*")
                    if len(g_list) == 2:
                        if (g_list[0] in key) and (g_list[1] in key):
                            host_graphs_list.append(graphs[key][0])
                    else:
                        if g_list[0] in key:
                            host_graphs_list.append(graphs[key][0])
            # host graphs is empty
            if not host_graphs_list:
                continue
            host_graphs_list.sort()
            graphs_dict[hostid] = host_graphs_list
        return graphs_dict

    def create_screen(self, HostList):
        graph_width = '200'
        graph_height = '100'
        screen_name='~Customer - ' + self.CustomerName
        # Check if Screen exist
        result = self.zapi.screen.exists({"name":screen_name})
        if result:
            info = 0
            return info

        screen_vsize = len(HostList)
        num = []
        for i in HostList:
            num.append(len(HostList[i]))
        screen_hsize = max(num)
        self.zapi.screen.create({"name": screen_name, "hsize": screen_hsize, "vsize": screen_vsize})
        screenid = self.zapi.screen.get({ "output": "screenid", "filter": { "name": screen_name} })[0]['screenid']

        y = 0
        for h in HostList:
            x = 0
            for g in range(0, len(HostList[h])):
                screen_items = {"screenid": screenid,
                                    "resourcetype": 0,
                                    "resourceid": HostList[h][g],
                                    "width": graph_width,
                                    "height": graph_height,
                                    "x": x,
                                    "y": y
                                }
                self.zapi.screenitem.create(screen_items)
                x += 1
            y += 1
        info = 1
        return info

    def delete_screen(self, HostList):
        screen_name = '~Customer - ' + self.CustomerName
        # Check if Screen exist
        result = self.zapi.screen.exists({"name":screen_name})
        if not result:
            del_info = 1
            return del_info
        screen_id = self.zapi.screen.get({"output": "screenid", "filter": { "name": screen_name}})[0]['screenid']
        screen_arr = [screen_id]
        try:
            del_info = self.zapi.screen.delete(screen_arr)
        except ZabbixAPIException, e:
            info = e
        if type(del_info) == "tuple":
            return del_info
        else:
            return 0
